package sf.database.jdbc.sql;

import sf.database.dao.DBContext;
import sf.database.jdbc.handle.RowListHandler;
import sf.database.jdbc.handle.SingleRowHandler;
import sf.database.jdbc.rowmapper.MapRowMapper;
import sf.database.jdbc.rowmapper.RowMapper;
import sf.database.jdbc.rowmapper.RowMapperHelp;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * 帮助方法,简化jdbc的使用
 */
public class CommonResult {
    /**
     * 提取List结果
     * @param rs        jdbc结果集
     * @param beanClass 返回类型
     * @param context   可为null
     * @param <T>       泛型
     * @return 结果
     */
    public static <T> List<T> getListResult(ResultSet rs, Class<T> beanClass, DBContext context) {
        RowMapper<T> rowMapper = RowMapperHelp.getRowMapper(beanClass, context);
        ResultSetCallback<List<T>> rsh = new RowListHandler<>(rowMapper);
        try {
            return rsh.callback(rs);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 提取List结果
     * @param rs jdbc结果集
     * @return 结果
     */
    public static List<Map<String, Object>> getListMapResult(ResultSet rs) {
        ResultSetCallback<List<Map<String, Object>>> rsh = new RowListHandler<>(new MapRowMapper());
        try {
            return rsh.callback(rs);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 提取单个结果
     * @param rs        jdbc结果集
     * @param beanClass 返回类型
     * @param context   可为null
     * @param <T>       泛型
     * @return 结果
     */
    public static <T> T getOneResult(ResultSet rs, Class<T> beanClass, DBContext context) {
        RowMapper<T> rowMapper = RowMapperHelp.getRowMapper(beanClass, context);
        ResultSetCallback<T> rsh = new SingleRowHandler<>(rowMapper);
        try {
            return rsh.callback(rs);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 提取单个结果
     * @param rs jdbc结果集
     * @return 结果
     */
    public static Map<String, Object> getOneMapResult(ResultSet rs) {
        ResultSetCallback<Map<String, Object>> rsh = new SingleRowHandler<>(new MapRowMapper());
        try {
            return rsh.callback(rs);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
